/**
 * Created by George on 2014/9/14.
 */
'use strict';

var mysql = require('../common/mysql.js');

/*
 @todo 判断tid对应贴子是否存在
 */
exports.isThreadExist = function*(tid) {
    var isExist = false;
    var result = yield mysql.query('SELECT pid FROM mh_thread WHERE tid=?', [tid]);
    if (result.length > 0) {
        isExist = true;
    }
    return isExist;
};

/*
 @todo 修改主题贴信息
 @fields 修改字段 格式为field1=?，field2=?...
 @where  查找条件 格式为field1=? and field=?
 @values 条件值   格式为[value1，value2]
 */
exports.editThread = function*(fields, where, values) {
    var flag = yield mysql.query("update mh_thread set " + fields + " where " + where, values);
    if (flag.affectedRows > 0) {
        return true;
    }
    return false;
};

/*
 @todo 修改回复贴信息
 @fields 修改字段 格式为field1=?，field2=?...
 @where  查找条件 格式为field1=? and field=?
 @values 条件值   格式为[value1，value2]
 */
exports.editPost = function*(fields, where, values) {
    var flag = yield mysql.query("update mh_post set " + fields + " where " + where, values);
    if (flag.affectedRows > 0) {
        return true;
    }
    return false;
};

/*
 @todo 判断贴子是否被某人点赞过
 @ pid
 @uid
 */
exports.isLike = function*(pid, uid) {
    var likeData = yield mysql.query("SELECT uid FROM mh_likes WHERE uid=? AND pid=?", [uid, pid]);
    if (likeData.length > 0) {
        return true;
    }
    return false;
};

/*
 @todo 根据组织名称返回id
 @ orgObj object
 */
exports.getOrgid = function*(orgObj) {
    var orgId = 0;//初始化组织id
    var orgData = yield mysql.queryOne('SELECT orgid FROM mh_organization WHERE organization=? AND citycode=?', [orgObj.organization, parseInt(orgObj.citycode)]);
    if (orgData) {
        orgId = orgData['orgid'];
    } else {
        var temp = yield mysql.query('INSERT INTO mh_organization(organization,citycode,contact) VALUES(?,?,?)', [orgObj.organization, parseInt(orgObj.citycode), orgObj.contact]);
        if (temp.insertId > 0) {
            orgId = temp.insertId;
        }
    }
    return orgId;
};

/*
 @todo 取得某个帖子的回复用户
 @ orgObj object
 */
exports.getPostUsers = function*(fields) {
    var returnData = [];
    var tid = fields.tid;
    var beginIndex = 0;
    var pageSize = 3;
    if (fields.beginIndex) {
        beginIndex = parseInt(fields.beginIndex);
    }
    if (fields.pageSize) {
        pageSize = parseInt(fields.pageSize);
    }
    var postUserseData = yield mysql.query('SELECT mp.uid,ifnull(SUBSTR(mpc.post FROM 1 FOR 30),"") post,mu.nickname FROM mh_post mp LEFT JOIN mh_post_content mpc ON mp.pid=mpc.pid LEFT JOIN mh_user mu ON mp.uid=mu.uid WHERE mp.tid=? AND mp.`first`=0 AND mp.`status`=1 ORDER BY mp.pid DESC LIMIT ?,?', [parseInt(tid), beginIndex, pageSize]);
    if (postUserseData.length > 0) {
        returnData = postUserseData;
    }
    return returnData;
};